package stancel.peter.smslogger;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

/**
 * Vytvara vzhlad prvkov nachadzajucich sa v liste triedy <b>ContactsActivity</b>.
 * @author Peter Stancel
 */
public class ContactsAdapter extends ArrayAdapter<Contact>{

	private List<Contact> list;
	private LayoutInflater inflater;
	
	/**
	 * Konstruktor.
	 * @param context Context
	 * @param list List kontaktov.
	 */
	public ContactsAdapter(Context context, List<Contact> list) {
		super(context, 0, list);
		this.list = list;
		this.inflater = LayoutInflater.from(context);
	}
	
	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Contact getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/**
	 * Vytvara vzhlad jednej polozky listu v <b>ContactsActivity</b>.
	 * Prida OnClickListener na kazdu polozku listu - nastavuje premennu <i>checked</i>
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Contact contact = list.get(position);
		View listView = inflater.inflate(R.layout.list_contact_adapter, null);
		
		listView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(contact.isChecked()){
					contact.setChecked(false);
				}else{
					contact.setChecked(true);
				}
				notifyDataSetChanged();
			}
		});
		
		TextView tv = (TextView) listView.findViewById(R.id.contact_name);
		tv.setText(contact.getName());
		
		tv = (TextView) listView.findViewById(R.id.contact_number);
		tv.setText(contact.getNumber());
		
		CheckBox checkBox = (CheckBox) listView.findViewById(R.id.contact_checkbox);
		checkBox.setChecked(contact.isChecked());
		
		return listView;
	}
}
